package day0518;

import java.sql.Connection;
import java.sql.SQLException;

import java.sql.PreparedStatement;
import com.zretc.tools.DBTools;

public class TestTrans {

	public static void main(String[] args) {
		// 测试事务处理
		// 连接对象
		Connection conn = DBTools.getConn();
		try {
			// 设置边界 setAutoCommit,表示不再自动提交，而是手动提交
			conn.setAutoCommit(false);

			// 主体业务代码...[转账 两条sql执行]
			String sql1 = "update t_account set balance = balance - 1 where accountname = '张三丰'";
			// 创建PreparedStatement
			PreparedStatement pstmt = conn.prepareStatement(sql1);

			int n1 = pstmt.executeUpdate();
			
			String str = null;
			//System.out.println(str.length());//NullpointException
			

			String sql2 = "update t_account set balance = balance + 1 where accountname = '张三'";
			
			pstmt = conn.prepareStatement(sql2);

			int n2 = pstmt.executeUpdate();
			
			if (n1 == 1 &&n2 ==1) {
				// 事务提交
				conn.commit();
				System.out.println("转账成功,事务提交!");
			}
			else {
				conn.rollback();
				System.out.println("转账失败，事务回滚!");
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// 事务回滚
			try {
				conn.rollback();
				System.out.println("转账失败，事务回滚!");
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// e.printStackTrace();
		}

	}

}